package com.ddpt.platform.common.util;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ObjectUtil {

    /**
     * 获取对象中的所有属性
     * @param bean	对象
     * @return	属性和值(Map[属性名, 属性值])
     */
    public static Map<String, Object> getAttributes(Object bean) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            for(Class<?> clazz=bean.getClass(); !clazz.equals(Object.class); clazz=clazz.getSuperclass()) {
                Field[] fs = clazz.getDeclaredFields();
                for(Field f : fs) {
                    // 子类最大，父类值不覆盖子类
                    if(map.containsKey(f.getName())) {
                        continue;
                    }
                    f.setAccessible(true);
                    Object value = f.get(bean);
                    f.setAccessible(false);
                    map.put(f.getName(), value);
                }
            }
            map.remove("serialVersionUID");
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取对象中的所有非空字段
     */
    public static Map<String, Object> getNotNullAttributes(Object bean){
        Map<String,Object> result = new HashMap<>();
        Map<String, Object> map = getAttributes(bean);
        for (Map.Entry<String, Object> next : map.entrySet()) {
            String key = next.getKey();
            Object value = next.getValue();
            if (StringUtils.isBlank(key) || value == null) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }
}
